<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar
      :is-white="false"
      :title="navTitle"
      :custom-back="goBack"
      style="z-index: 99999"
    >
    </theme-navbar>
    <!-- #endif -->

    <view class="content u-page" style="padding-bottom: 140rpx;">
      <view class="card">
        <view
          class="group-tag"
          v-for="(item, index) of coordTypeList"
          :key="index"
        >
          <view class="group-name">{{ item.coordTypeName }}</view>
          <view class="group-tag-list">
            <u-tag
              v-for="tagItem of item.tags"
              :text="tagItem.text"
              :key="tagItem.value"
              style="margin: 0 20rpx 20rpx 0; padding: 18rpx 22rpx; font-size: 28rpx;"
              :mode="selectedTags.indexOf(tagItem.value) > -1 ? 'dark' : 'plain'"
              @click="handleTagClick(tagItem)"
            />
          </view>
        </view>
      </view>

      <view class="card" style="padding-top: 25rpx; padding-bottom: 25rpx;">
        <view style="font-weight: 600;">异常信息描述</view>
        <view>
          <u-input type="textarea" v-model="formData.exceptionDesc" />
        </view>
        <view style="font-weight: 600;">需要分析研判内容</view>
        <view>
          <u-input type="textarea" v-model="formData.needJudgmentContent" />
        </view>
        <view>
          <upload-images
            :url="uploadFile"
            :length="10"
            :extForm="{fiGroupCode: $FILE_GROUP_TYPE.three_teamwork_img, bizId: formData.taskUuid}"
            :bizId="formData.taskUuid"
            :del-url="delUrl"
            :can-add="true"
            :can-del="true"
            :renderImages="renderImages"
            ref="saveModel3"
            style="padding-left: 0;"
          ></upload-images>
        </view>

      </view>

    </view>

    <!-- 底部按钮 -->
    <view class="submit-btns btn-other-cls">
      <u-button class="u-btn" @click="handleSaveBtn">保存</u-button>
      <u-button class="u-btn" type="primary" @click="handleSubmitBtn">
        提交
      </u-button>
      <u-button class="u-btn" v-if="isShowBtn" type="error" @click="handleCancelBtn">
        作废
      </u-button>
    </view>

  </view>
</template>

<script>
// import commonService from "@/service/common/common.service.js";
import commonService from '@/service/eCigar/common.service';
import certificateService from "@/service/certificate/certificate.service.js";
import threePostsJointActionService from "@/service/threePostsJointAction/threePostsJointAction.service.js";
import clientItem from "./components/client-item.vue";
import { UploadImages } from "@/components";
import UInput from "../../uview-ui/components/u-input/u-input.vue";

export default {
  components: {
    UInput,
    clientItem,
    UploadImages,
  },
  data() {
    return {
      taskSubject: 0,
      taskSubjectList: [{ name: "零售户" }, { name: "无证户" }], // 任务对象 01：零售户、02：无证户
      formData: {
        taskUuid: ""
      },
      uploadFile: commonService.uploadFile,
      delUrl: commonService.deleteFile,
      urgentStatusList: [
        { text: "一般", value: "01" },
        { text: "紧急", value: "02" },
        { text: "特急", value: "03" },
      ],
      selectedUrgent: "", // 任务紧急状态
      retailerList: [],
      swipeOptions: [
        {
          text: "删除",
          style: {
            backgroundColor: "#dd524d",
          },
        },
      ],
      allBusinessList: [], // 所有业务指标
      businessTabList: [],
      tabCurrent: 0,
      selectedTags: [],
      actionType: "", // 操作类型
      isShowBtn: false
    };
  },
  computed: {
    coordTypeList() {
      let currCoordTypeList = [];
      if (this.allBusinessList.length) {
        currCoordTypeList = this.allBusinessList[this.tabCurrent].coordTypeList;

        currCoordTypeList.map(item => {
          item.tags = item.coordItemList.map(coordItem => {
            return { text: coordItem.itemName, value: coordItem.itemUuid }
          })
        })
      }

      return currCoordTypeList;
    }
  },
  onLoad(options) {
    let routeParams = this.getRouteParam();
    if (options.taskUuid) {
      this.formData.taskUuid = options.taskUuid;
    } else if (routeParams.taskUuid) {
      this.formData.taskUuid = routeParams.taskUuid;
    }
    this.isShowBtn = this.formData.taskUuid;
    this.initData(this.formData.taskUuid);
  },
  methods: {
    initData(taskUuid) {
      this.$modal.showLoading('加载中...');
      Promise.all([
        threePostsJointActionService.getMSJointActionTaskInfo({ taskUuid }),
        threePostsJointActionService.getJointActionTaskItem({ taskUuid })
      ]).then(([res1, res2]) => {
        this.$modal.hideLoading();

        if (res1.success) {
          if(!taskUuid) {
            this.formData = {...res1.bean};
          } else {
            // 详情
            const {  tasklist: { itemUuidArray } } = res1.bean;
            // this.retailerList = [licenseList];
            // this.selectedUrgent = taskUrgencyLevel; // 任务紧急状态
            // this.taskSubject = Number(taskSubject.split("0")[1]) - 1;
            this.selectedTags = itemUuidArray;
            this.formData = { ...res1.bean.tasklist };
          }
        } else {
          this.$u.toast(res1.msg);
        }

        // 所有指标类型
        if (res2.success) {
          this.allBusinessList = res2.data;
          this.businessTabList = res2.data.map(item => {
            return {name: item.businessName}
          });

          let tabCurrent = this.allBusinessList.findIndex(item => item.businessType === this.formData.businessType);
          this.tabCurrent = tabCurrent > -1 ? tabCurrent : 0;
        } else {
          this.$u.toast(res2.msg);
        }
      }).catch(() => {
        this.$u.toast("数据获取失败!");
        this.$modal.hideLoading();
      });
    },
    handleTaskSubjectChange(e) {
      this.taskSubject = e;
      this.retailerList = [];
    },
    handleUrgentStatusClick(data) {
      this.selectedUrgent = data.value;
    },
    handleTabChange(e) {
      this.tabCurrent = e;
      this.selectedTags = []; // 清空选中的标签
    },
    handleTagClick(data) {
      if (this.selectedTags.indexOf(data.value) > -1) {
        this.selectedTags = this.selectedTags.filter(item => item != data.value);
      } else {
        this.selectedTags.push(data.value);
      }
    },
    handleSearchFocus() {
      let url = "/pages/commonPage/selectRetailer";
      if (this.taskSubject === 1) {
        url = "/pages/commonPage/selectUnlicenseRetailer";
      }
      this.$u.route({ url });
      
    },
    handleMapSelect() {
      if (this.taskSubject === 1) {
        this.$u.toast("无证户不支持地图定位!");
        return;
      }
      this.$u.route({
        url: "/pages/commonPage/selectRetailerMap",
      });
    },
    onScan() {
      // #ifdef H5-DINGDING || H5-WECHAT || H5-EMP
      this.$deviceApi
        .scan()
        .then((res) => {
          let licNo = res.replace(/ +/g, "").replace(/[\r\n]/g, "");
          try {
            let start = licNo.indexOf("许可证号") + 5;
            let num = licNo.indexOf("发证机关") - start;
            licNo = licNo.substr(start, num);
          } catch (e) {
            console.log(e);
          }
          if (!this.$u.test.digits(licNo)) {
            this.$u.toast("解析失败");
            return;
          }
          certificateService
            .getRetailerListByLicenseCodes({ licNoStr: licNo })
            .then((rt) => {
              if (rt.success && rt.data.length > 0) {
                let data = res.data[0];
                let allLicNo = this.retailerList.map(item => item.licNo);
                if (allLicNo.indexOf(data.licNo) > -1) {
                  this.$u.toast(data.companyName + "已存在列表!");
                } else {
                  this.retailerList.push(itm);
                }
              } else {
                this.$u.toast(rt.msg);
              }
            })
            .catch((error) => {
              this.$u.toast(error);
            });
        })
        .catch((err) => {
          this.$u.toast("扫描失败");
        });
      // #endif
    },
    updateBackState(param) {
      if (param["selectRetailer"]) {
        // 选择零售户回调
        this.retailerList = param.selectRetailer;
      } else if (param["selectRetailerMap"]) {
        // 地图选择零售户回调
        this.retailerList = param.selectRetailerMap;
      } else if (param["flowUserSelectBack"]) {
        // 审核人员选择回调
        this.nextPersonUuids = param["flowUserSelectBack"].map(item => item.personId).join(",");
        let paras = this.validatePageData();
        this.saveCoordinationTask(paras);
      }
    },
    handleSwipeOpen(index) {
      this.retailerList[index].show = true;
      this.retailerList = this.retailerList.map((item, listIndex) => {
        if (listIndex != index) {
          item.show = false;
        }
        return item;
      })
    },
    handleDeleteClient(idx) {
      this.retailerList.splice(idx, 1);
    },
    renderImages(){
			return new Promise((res, rej) => {
          commonService.findFilesByBizId(this.$FILE_GROUP_TYPE.three_teamwork_img, this.formData.taskUuid).then(r => {
					if(r.code == 200 && r.success && Array.isArray(r.data)) {
						r.data.forEach(i => {
							i.src = `${commonService.baseUrl}/commonfile/filestore/downloadFile.do?fileId=${i.gfiId}&tk=${uni.getStorageSync("tk")}`;
              i.filePath = i.src;
						});
						res(r.data);
					} else {
					 res([]);
					}
				});
			})
    },
    validatePageData() {
      if (!this.selectedTags.length) {
        this.$u.toast("请选择问题类型!");
        return;
      } else {
        let taskSubject = this.taskSubject + 1;
        let paras = {
          ...this.formData,
        //  taskSubject: "0"+taskSubject, // 01：零售户；02：无证户
        //  retailerUuid: this.retailerList[0].retailerUuid,
        //  businessType: this.allBusinessList[this.tabCurrent].businessType, // 指标大类
        //  taskUrgencyLevel: this.selectedUrgent, // 任务紧急状态
          checkedItemList: this.selectedTags, // 协同问题集合
          nextPersonUuids: this.nextPersonUuids, // 下一步审核人uuid
        };
        return paras;
      }
    },
    handleSaveBtn() {
      this.actionType = "save";
      let paras = this.validatePageData();
      if (!paras) {
        return;
      }
      this.saveCoordinationTask(paras);
    },
    saveCoordinationTask(paras) {
      this.$modal.showLoading('数据保存中...');
      let actionTypeMsg = this.actionType === 'save' ? '保存' : '提交';
      threePostsJointActionService.saveJointActionTask(paras).then(res => {
        this.$modal.hideLoading();
        if (res.success) {
          this.$u.toast(actionTypeMsg + "成功!");
          setTimeout(() => {
            this.backPrev({
              paramKey: "submitSuccess",
              param: true
            });
          }, 1000);
        } else {
          this.$u.toast(res.msg);
        }
      }).catch(() => {
        this.$u.toast(actionTypeMsg + "失败!");
        this.$modal.hideLoading();
      })
    },
    // 获取流程获选人参数
    getNextFlowUsersExtData() {
      this.$modal.showLoading("获取候选人中...");
      console.log(this.formData);
      threePostsJointActionService.getNextFlowUsersExtData({
        taskUuid: this.formData.taskUuid
      }).then(res => {
        if (res.success) {
          let flowCode = "jointActionTask";
          let extParams = res.bean || {};
          this.setRouteParam({
            ...extParams
          });
          this.$u.route({
            url: "/pages/commonPage/flowUserSelectComponent",
            params: {
              flowFormCode: flowCode,
              // docInsUuid: this.formData.taskUuid
            }
          });
        } else {
          this.$u.toast(res.msg);
        }
      }).catch(() => {
        this.$u.toast("候选人获取失败!");
      })
    },
    handleSubmitBtn() {
      this.actionType = "submit";
      let valid = this.validatePageData();
      if (!valid) {
        return;
      }
      this.getNextFlowUsersExtData();
    },
    handleCancelBtn(){
      this.actionType = "error";
      let paras = {
        ...this.formData,
      }
      this.cancelJointActionTask(paras);
    },
    cancelJointActionTask(paras){
      this.$modal.showLoading('数据作废中...');
      threePostsJointActionService.cancelJointActionTask(paras).then(res => {
        this.$modal.hideLoading();
        if (res.success) {
          this.$u.toast("数据作废成功!");
          setTimeout(() => {
            this.backPrev({
              paramKey: "submitSuccess",
              param: true
            });
          }, 1000);
        } else {
          this.$u.toast(res.msg);
        }
      }).catch(() => {
        this.$u.toast("作废失败!");
        this.$modal.hideLoading();
      })
    }
  },
};
</script>

<style lang="scss" scoped>
.page {
  padding: 0;
}
.content {
  background-color: #f3f4f5;
}

.card {
  margin-left: 0;
  margin-right: 0;
  border-radius: 0;
  padding-left: 25rpx;
  padding-right: 25rpx;
}

.group-tag {
  .group-name {
    font-size: 30rpx;
    font-weight: 600;
    margin: 20rpx 0 18rpx;
  }
}
</style>